package com.bw.demo_flow

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class FlowActivity : AppCompatActivity() {

    private val mainVIewModel by viewModels<MyViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flow)
        val textView = findViewById<TextView>(R.id.text_view)
        val button = findViewById<Button>(R.id.button)
        button.setOnClickListener {
            //第一种方法
//            lifecycleScope.launch {
//                launch {
//                    mainVIewModel.timeFlow.collect {
//                        textView.text = "$it"
//                    }
//                }
//
//                launch {
//                    mainVIewModel.timeFlow2.collect {
//                        Toast.makeText(this@FlowActivity, "$it", Toast.LENGTH_SHORT).show()
//                    }
//                }
//            }

            //第二种方法
//            lifecycleScope.launchWhenStarted {
//                mainVIewModel.timeFlow.collect {
//                    textView.text = "$it"
//                }
//            }

            //第三种方法
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED){
                    mainVIewModel.timeFlow.collect {
                        textView.text = "$it"
                    }
                }
            }
        }
    }
}